package cn.edu.tsinghua.smxq.mobilecity.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.edu.tsinghua.smxq.mobilecity.po.BankAccount;
import cn.edu.tsinghua.smxq.mobilecity.po.User;
import cn.edu.tsinghua.smxq.mobilecity.utils.DBUtils;
import cn.edu.tsinghua.smxq.mobilecity.utils.DateUtils;

public class BankAccountDAO {
	
	public boolean update(BankAccount bankAccount) throws SQLException {
		boolean success = false;
		Connection conn = DBUtils.Connect();
		PreparedStatement pstmt = conn
				.prepareStatement("UPDATE mobilecity.bankaccount SET password=?,deposits=?,recentoperationtime=? WHERE cardno=?");
		pstmt.setString(1, bankAccount.getPassword());
		pstmt.setFloat(2, bankAccount.getDeposits());
		pstmt.setTimestamp(3, DateUtils.getSystemNowTime());
		pstmt.setString(4, bankAccount.getCardNo());
	
		if (pstmt.executeUpdate() == 1) {
			success = true;
		}
		pstmt.close();
		conn.close();
		return success;
	}
	
	public BankAccount getByCardNo(String cardNo) throws SQLException{
		BankAccount bankAccount=null;
		Connection conn = DBUtils.Connect();
		ResultSet rs = null;
		PreparedStatement pstmt = conn
				.prepareStatement("SELECT * FROM mobilecity.bankaccount WHERE cardno=?");
		pstmt.setString(1, cardNo);
		rs = pstmt.executeQuery();
		if (rs.next()) {
			bankAccount = new BankAccount();
			bankAccount.setCardNo(rs.getString("cardno"));
			bankAccount.setPassword(rs.getString("password"));
			bankAccount.setDeposits(rs.getFloat("deposits"));
			bankAccount.setRegistrationDate(rs.getDate("registrationdate"));
			bankAccount.setRecentOperationTime(rs.getTimestamp("recentoperationtime"));
		}
		rs.close();
		pstmt.close();
		conn.close();
		return bankAccount;
	}
	
	public BankAccount getByCardNoPassword(String cardNo,String password) throws SQLException{
		BankAccount bankAccount=null;
		Connection conn = DBUtils.Connect();
		ResultSet rs = null;
		PreparedStatement pstmt = conn
				.prepareStatement("SELECT * FROM mobilecity.bankaccount WHERE cardno=? and password=?");
		pstmt.setString(1, cardNo);
		pstmt.setString(2, password);
		rs = pstmt.executeQuery();
		if (rs.next()) {
			bankAccount = new BankAccount();
			bankAccount.setCardNo(rs.getString("cardno"));
			bankAccount.setPassword(rs.getString("password"));
			bankAccount.setDeposits(rs.getFloat("deposits"));
			bankAccount.setRegistrationDate(rs.getDate("registrationdate"));
			bankAccount.setRecentOperationTime(null);
		}
		rs.close();
		pstmt.close();
		conn.close();
		return bankAccount;
	}

}
